String.prototype.startWith = function(compareStr){
	return this.indexOf(compareStr) == 0;
}
$(function(){
	$("select[name$='.queryCondition']").each(function(){
		var options = "";
		options+="<option value='='>等于</option>";
		options+="<option value='!='>不等于</option>";
		options+="<option value='>'>大于</option>";
		options+="<option value='>='>大于等于</option>";
		
		options+="<option value='<'>小于</option>";
		options+="<option value='<='>小于等于</option>";
		options+="<option value='contains'>包含</option>";
		options+="<option value='uncontains'>不包含</option>";
		options+="<option value='prefix'>前缀</option>";
		options+="<option value='suffix'>后缀</option>";
		$(this).append(options);
	});
	var validator = $("#queryForm").validate({
		errorElement: "title",
		ignoreTitle: true,
		submitHandler : function(form){
			var actionUrl = $(form).attr("action");
			if(actionUrl){
				return true;
			}else{
				queryFormSubmit();
			}
		},
		rules:{
			/*outHospitalStartDate: {
				required: true
            },
            outHospitalEndDate: {
				required: true
            }*/
		}
		
	});
	$("#query_div select[name='items[0].queryCode']").change(function(){
		var queryCodeValue = $(this).val();
		var queryValueObj = $(this).parent().parent().find("input[name$='.queryValue']");
		var queryValueObjParent = queryValueObj.parent();
		var newQueryValueObj = $("#template_value").clone();
		newQueryValueObj.removeAttr("id");
		newQueryValueObj.attr("name",queryValueObj.attr("name"));
		queryValueObj.remove();
		queryValueObjParent.append(newQueryValueObj);
		/*queryValueObj.val(null).removeAttr("onclick").remove("blur").remove("mousedown").remove("unload").rules("remove");*/
		if(queryCodeValue.startWith("date_")){
			/*alert($(this).parent().parent().find("input[name$='.queryValue']").attr("name"));*/
			newQueryValueObj.attr("onclick","WdatePicker();");
		}else if(queryCodeValue.startWith("int_")){
			newQueryValueObj.rules("add",{range:[1,1000],digits:true});
		}else if(queryCodeValue.startWith("float_")){
			newQueryValueObj.rules("add",{range:[1,10000],number:true});
		}
		/*alert(queryCodeValue);*/
		
		
	}).select2();
	
});
/*点击查询按钮*/
function queryBtnClick(){
	$("#queryForm").attr("action",null);
	$("#queryForm").submit();
}

/*提交查询*/
function queryFormSubmit(){
	
	var submitData = $('#queryForm').serialize();
	var basePath = $("#basePath").val();
	layer.load(1,{offset: '200px'});
	$("#export_h").html("");
	clearPage();
	$.ajax({
		url: basePath + "medical_record_searching/ajax_custom_searching",
		dataType: "json",
		data:submitData,
		success: function( data ) {
			var success = data['success'];
			
			if(success){
				var params = data['data'];
				var totalCounts = params['totalCounts'];
				if(totalCounts > 0){
					layer.msg("检索成功",{offset: '200px'});
					var medicalRecords = params['datas'];
					addRows(medicalRecords);
					var pageSize = params['pageSize'];
					var currentPage = params['currentPage'];
					if(totalCounts > 0){
						$("#export_h").html("<input type='button' value='导出' onclick='exportToExcel()'/>");
					}
					initPage(parseInt(totalCounts),parseInt(pageSize),parseInt(currentPage));
				}else{
					layer.msg("检索结果为空",{offset: '200px'});
				}
	            
			}else{
				layer.msg("检索失败",{offset: '200px'});
			}
			console.log(data);
			
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			layer.msg("未知错误，请联系管理员",{offset: '200px'});
		},
		complete:function(XMLHttpRequest, textStatus){
			layer.closeAll('loading');
		}
	});
	
};

/*添加列表行*/
function addRows(medicalRecords){
	for(var index in medicalRecords){
		var medicalRecord = medicalRecords[index];
		var add_content=$("#template_tr").clone();
		add_content.removeAttr("hidden");
		add_content.attr("id",medicalRecord.visitGuid);
		add_content.find("span[class='only_id']").html(medicalRecord.onlyId);
		add_content.find("span[class='mr_id']").html(medicalRecord.mrId);
		add_content.find("span[class='visit_number']").html(medicalRecord.visitNumber);
		add_content.find("span[class='patient_name']").html(medicalRecord.patientName);
		add_content.find("span[class='id_number']").html(medicalRecord.idNumber);
		
		add_content.find("span[class='out_dept_name']").html(medicalRecord.outDeptName);
		add_content.find("span[class='out_hospital_date']").html(medicalRecord.outHospitalDateTime);
		add_content.find("span[class='str_out_hospital_type']").html(medicalRecord.outHospitalTypeName);
		add_content.find("span[class='in_hospital_day_number']").html(medicalRecord.inHospitalDayNumber);
		add_content.find("span[class='total_cost_money']").html(medicalRecord.totalCostMoney);
		$("#query_show_table tbody").append(add_content);
    } 
	
}

/*清空列表和分页控件*/
function clearPage(){
	$("#template_tr").siblings("tr").remove();
	$("#page_plus").html("");
	$("#totalPage").html("0");
    $("#currentPage").html("0/0");
}

/*初始化分页控件*/
function initPage(totalCounts,pageSize,currentPage){
	 var visiblePages = 5;
	 var totalPages =  totalCounts%pageSize==0?(totalCounts/pageSize):(parseInt(totalCounts/pageSize)+1);
	 if(totalCounts < 1){
		$("#page_plus").html("");
		$("#totalPage").html("0");
        $("#currentPage").html("0/0");
	 }else{
		 $('#page_plus').jqPaginator({

	        totalCounts: totalCounts,
	        pageSize:pageSize,
	        visiblePages: visiblePages,
	        currentPage: currentPage,

	        first:'<li class="first"><a href="javascript:void(0);">首页</a></li>',
	        prev: '<li class="prev"><a href="javascript:void(0);">上一页</a></li>',
	        next: '<li class="next"><a href="javascript:void(0);">下一页</a></li>',
	        last: '<li class="last"><a href="javascript:void(0);">末页</a></li>',
	        page: '<li class="page"><a href="javascript:void(0);">{{page}}</a></li>',
	        onPageChange: function (num,type) {

	     		if(type !='init'){
	     			$("input[name='currentPage']").val(num);
	     			queryFormSubmit();
				}
	            $("#totalPage").html(totalCounts);
	            $("#currentPage").html(num+"/"+totalPages);
	        }
	    });
	 }
}


function addQuery(){
	var copy_content = $("#queryTemplate").clone();
	copy_content.removeAttr("id");
	
	copy_content.find("span[title='delete']").parent().click(function() {
		deleteQuery(this);
	});
	var queryCount = parseInt($("#queryCount").val());
	$.each(copy_content.find("input[name^='items[0].'],select[name^='items[0].']"), function(i,item) {    
    	var inputName = $(item).attr("name");
    	var changeName = inputName.replace("items[0].","items["+queryCount+"].");
        $(item).attr("name",changeName);
    });
	copy_content.find("select[name$='.queryCode']").change(function(){
		var queryCodeValue = $(this).val();
		var queryValueObj = $(this).parent().parent().find("input[name$='.queryValue']");
		var queryValueObjParent = queryValueObj.parent();
		var newQueryValueObj = $("#template_value").clone();
		newQueryValueObj.removeAttr("id");
		newQueryValueObj.attr("name",queryValueObj.attr("name"));
		queryValueObj.remove();
		queryValueObjParent.append(newQueryValueObj);
		/*queryValueObj.val(null).removeAttr("onclick").remove("blur").remove("mousedown").remove("unload").rules("remove");*/
		if(queryCodeValue.startWith("date_")){
			/*alert($(this).parent().parent().find("input[name$='.queryValue']").attr("name"));*/
			newQueryValueObj.attr("onclick","WdatePicker();");
		}else if(queryCodeValue.startWith("int_")){
			newQueryValueObj.rules("add",{range:[1,1000],digits:true});
		}
		/*alert(queryCodeValue);*/
		
		
	}).select2();
    $("#queryCount").val(queryCount+1);
    
	$("#query_div").append(copy_content);
}


function deleteQuery(obj){
	$(obj).parent().parent().parent().remove();
}

function exportToExcel(){
	var basePath = $("#basePath").val();
	$("#queryForm").attr("action",basePath+"medical_record_searching/custom_searching_export_excel");
	$("#queryForm").submit();
}

function pageIndexShow(obj){
	var basePath = $("#basePath").val();
	 var content = $(obj).parent().parent();
	 var visitGuid = content.attr("id");
	window.open(basePath+'medical_record_coding/show_home_page_index?visitGuid='+visitGuid);
}